/*
 * PsCutTime.cpp
 *
 *  Created on: 2018年7月13日
 *      Author: zhengboyuan
 */

#include "PsCutTime.h"

static size_t   MAX_PES_LENGTH = 0xFFFF;

PsCutTime::PsCutTime()
{
    m_buffer.ensure(MAX_PES_LENGTH);
}

PsCutTime::~PsCutTime()
{
}

bool PsCutTime::cutTime(const PsPacket& pkt, PsPacket& outPkt)
{
    if (pkt.type != kPsPackHeader)
    {
        return false;
    }

    outPkt = pkt;

    ps_header* header = (ps_header*)pkt.data;
    if (header->pack_stuffing_length == 0)
    {
        return false;
    }

    m_buffer.clear();
    m_buffer.write(pkt.data, pkt.size);
    outPkt.data = m_buffer.data();
    outPkt.size = sizeof(ps_header);

    header = (ps_header*)outPkt.data;
    unsigned char stuf = header->pack_stuffing_length;

    header->pack_stuffing_length = 0;

    return true;
}

bool PsCutTime::cutTime(const char* filepath, const char* outPath)
{
    PsFileStream fs;
    if (!fs.open(filepath))
    {
        return false;
    }

    FILE* file = fopen(outPath, "wb");
    if (!file)
    {
        fs.close();
        return false;
    }

    PsPacket pkt = PsPacket();
    while (fs.read(pkt))
    {
        PsPacket outPkt = PsPacket();
        if (cutTime(pkt, outPkt))
        {
            fwrite(outPkt.data, 1, outPkt.size, file);
        }
        else
        {
            fwrite(pkt.data, 1, pkt.size, file);
        }
    }

    fclose(file);

    fs.close();
    return true;
}

